package com.lhl.jwt.security.filters;

import com.lhl.jwt.exception.JwtParamException;
import com.lhl.jwt.token.WxAuthenticationToken;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @className: com.lhl.jwt.security.filters.WxAppletAuthenticationFilter
 * @description: 用于用户认证的filter，但是真正的认证逻辑会委托给Provider
 * @author: king
 * @date: 2020-12-22 14:54
 **/
@Api(tags = "WxAppletAuthenticationFilter", produces = "WxAppletAuthenticationFilter")
@Slf4j
public class WxAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public WxAuthenticationFilter() {
        super(new AntPathRequestMatcher("/wxLogin", "POST"));
    }

    @Override
    public void afterPropertiesSet() {
        Assert.notNull(getAuthenticationManager(), "AuthenticationManager must be specified");
        Assert.notNull(getSuccessHandler(), "AuthenticationSuccessHandler must be specified");
        Assert.notNull(getFailureHandler(), "AuthenticationFailureHandler must be specified");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        String wxId = request.getParameter("wxId");
        String mobile = request.getParameter("mobile");
        String type = request.getParameter("type");
        if(StringUtils.isBlank(wxId)){
            log.error("wxId is null");
            throw new JwtParamException("wxId is null");
        }
        AbstractAuthenticationToken authRequest = new WxAuthenticationToken(wxId,mobile,type);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
